"""
聊天服务模块
处理聊天消息和响应逻辑
"""

import json
from services.car_service import CarService

class ChatService:
    def __init__(self):
        self.car_service = CarService()
        
    def process_stream_response(self, completion, user_input, user, session_id, conn):
        """
        处理流式响应
        :param completion: 大模型返回的流式响应
        :param user_input: 用户输入
        :param user: 用户信息
        :param session_id: 会话ID
        :param conn: 数据库连接
        :return: 生成器对象
        """
        ai_response = ""
        has_triggered_query = False
        
        for chunk in completion:
            if hasattr(chunk, 'model_dump_json'):
                if len(chunk.choices) > 0:
                    content = getattr(chunk.choices[0].delta, 'content', '') or ""
                    ai_response += content
                    
                    # 检查是否需要触发车辆查询
                    if self._should_trigger_car_query(user_input, ai_response, has_triggered_query):
                        has_triggered_query = True
                        yield from self._handle_car_query(ai_response, user_input)
                    
                    yield json.dumps(json.loads(chunk.model_dump_json()))
            else:
                yield json.dumps(chunk)
                
        # 保存AI响应到数据库
        if user:
            conn.execute(
                'INSERT INTO chat_messages (user_id, content, sender, session_id) VALUES (?,?,?,?)',
                (user['id'], ai_response, 'ai', session_id)
            )
            conn.commit()
            
    def _should_trigger_car_query(self, user_input, ai_response, has_triggered_query):
        """
        检查是否应该触发车辆查询
        :param user_input: 用户输入
        :param ai_response: AI响应
        :param has_triggered_query: 是否已触发查询
        :return: 是否应该触发查询
        """
        car_keywords = ["二手车", "买车", "车源"]
        return (any(keyword in user_input for keyword in car_keywords) and 
                "清晰您的需求" in ai_response and 
                not has_triggered_query)
                
    def _handle_car_query(self, ai_response, user_input):
        """
        处理车辆查询
        :param ai_response: AI响应
        :param user_input: 用户输入
        :return: 生成器对象
        """
        # 发送查询开始的消息
        yield json.dumps({
            "choices": [{
                "delta": {"content": "\n\n正在查询相关数据，请稍候..."}
            }]
        })
        
        try:
            # 使用车辆服务处理请求
            result = self.car_service.process_car_request(ai_response, user_input)
            
            if result["should_process"]:
                # 发送查询结果
                yield json.dumps({
                    "choices": [{
                        "delta": {"content": result["message"]}
                    }]
                })
                
                # 更新ai_response以包含查询结果
                ai_response += result["message"]
            else:
                yield json.dumps({
                    "choices": [{
                        "delta": {"content": "\n\n无需处理车辆请求"}
                    }]
                })
                
        except Exception as e:
            error_message = "\n\n抱歉，数据查询出现异常，请稍后重试。"
            yield json.dumps({
                "choices": [{
                    "delta": {"content": error_message}
                }]
            })
            ai_response += error_message 